﻿using Microsoft.Practices.Unity.Configuration;
using System;
using System.Configuration;
using System.Linq;
using System.IO;
using System.Reflection;
using Unity;
using Unity.Interception.ContainerIntegration;
using Unity.Interception.Interceptors.InstanceInterceptors.InterfaceInterception;

namespace NoteHelper.Utils
{
    public static class UnityHelper
    {
        public static IUnityContainer GetContainer()
        {
            var _unityContainer = new UnityContainer();
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap
            {
                ExeConfigFilename = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "CfgFiles\\Unity.Config.xml")
            };
            Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
            UnityConfigurationSection configSection = (UnityConfigurationSection)configuration.GetSection(UnityConfigurationSection.SectionName);
            configSection.Configure(_unityContainer, "defaultContainer");

            // Unity AOP
            Assembly assembly = Assembly.Load("NoteHelper.IBusiness");
            var interception = _unityContainer.AddNewExtension<Interception>().Configure<Interception>();
            var lst = assembly.GetExportedTypes().Where(t => t.IsInterface && t.IsSubinterfaceOfIServiceBase()).ToList();
            foreach (Type target in lst)
            {
                interception.SetInterceptorFor(target, new InterfaceInterceptor());
            }

            return _unityContainer;
        }

        private static bool IsSubinterfaceOfIServiceBase(this Type t)
        {
            var count = t.GetInterfaces().Count(item => item.Name == "IServiceBase`1");
            return count > 0;
        }
    }
}
